package kpi.javatraining6.gnatiuk.src.tester.readers;


import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.IOException;

public class ConfigDOMReader {
    private Document doc;
    private XPath xPath;
    private static ConfigDOMReader configDOMReader;

    private ConfigDOMReader() {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            doc = builder.parse("config.xml");
        } catch (ParserConfigurationException | SAXException | IOException e) {
            System.out.println("cant create parser");
            System.exit(1);
        }
        XPathFactory factory = XPathFactory.newInstance();
        xPath = factory.newXPath();
    }

    public static ConfigDOMReader getInstance() {
          if (configDOMReader == null) {
              configDOMReader = new ConfigDOMReader();
          }
          return configDOMReader;
    }

    public boolean isLoggerActive() {
        return Boolean.parseBoolean(parseString("//loggerIsActive/text()"));
    }

    public String getUserActionLog() {
        return parseString("//userActionLog/text()");
    }

    public String getExceptionsLog() {
        return parseString("//exceptionsLog/text()");
    }

    public String getAdminName() {
        return parseString("//adminName/text()");
    }
    private String parseString(String xPathExpression) {
        String result = "";
        try {
            XPathExpression expr = xPath.compile(xPathExpression);
            result = (String)expr.evaluate(doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            System.out.println("cant parse string");
            System.exit(1);
        }
        return result;
    }
}
